﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : MonoBehaviour
{
    [System.Serializable]
    public class Pool
    {
        public int DefaultSize = 8;
        public GameObject Prefab;
        Stack<GameObject> Prefabs=new Stack<GameObject>();
        public void InitialPool()
        {
            if (DefaultSize <= 0)
            {
                DefaultSize = 5;
            }
            for (int i = 1; i <= DefaultSize; i++)
            {
                GameObject obj = Instantiate(Prefab);
                obj.SetActive(false);
                Prefabs.Push(obj);
            }
        }

        public GameObject GetObject()
        {
            GameObject obj;
            if (Prefabs.Count != 0)
            {
                obj = Prefabs.Pop();
            }
            else
            {
                obj = Instantiate(Prefab);
            }
            obj.SetActive(true);
            //Debug.Log("PoolGet: " + obj.name+" "+Prefabs.Count);

            return obj;
        }

        public void RemoveObject(GameObject obj)
        {
            //Debug.Log("PoolRemove: " + obj.name+Prefabs.Count);
            obj.SetActive(false);
            Prefabs.Push(obj);
        }

        public void DestroyPool()
        {
            Prefabs.Clear();
        }
    }
    [System.Serializable]
    public class PoolwithName
    {
        public string Tag;
        public Pool thePool;
    };
    public List<PoolwithName> Pools;
    public Dictionary<string, Pool> RealPools/*=new Dictionary<string, Pool>()*/;
    private void Start()
    {
        RealPools = new Dictionary<string, Pool>();
        foreach(var item in Pools)
        {
            //Debug.Log("Manager: " + item.Name);
            RealPools.Add(item.Tag, item.thePool);
            RealPools[item.Tag].InitialPool();
        }
    }
}
